package com.java_foundation.util;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.BitSet;

/**
 * @program: java_foundation
 * @description: 解决url中 中文乱码问题
 * @author: xiongbangwen <Email>xiongbangwen@163.com</Email>
 * @create: 2020-06-20 22:00
 **/
public class URLEncoder {
    protected static final char[] hexadecimal = new char[]{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B',
            'C', 'D', 'E', 'F'};
    protected BitSet safeCharacters = new BitSet(256);

    public URLEncoder(){
        char i;
        for (i='a';i<='z';i++){
            this.addSafeCharacter(i);
        }
        for (i = 'A'; i <= 'Z'; ++i) {
            this.addSafeCharacter(i);
        }

        for (i = '0'; i <= '9'; ++i) {
            this.addSafeCharacter(i);
        }
    }

    public void addSafeCharacter(char i) {
        this.safeCharacters.set(i);
    }

    public String encode(String path) {
        int maxBytesPerChar = 10;
//		boolean caseDiff = true;
        StringBuffer rewrittenPath = new StringBuffer(path.length());
        ByteArrayOutputStream buf = new ByteArrayOutputStream(maxBytesPerChar);
        OutputStreamWriter writer = null;

        try {
            writer = new OutputStreamWriter(buf, "UTF8");
        } catch (Exception e) {
            e.printStackTrace();
            writer = new OutputStreamWriter(buf);
        }

        for (int i = 0; i < path.length(); ++i) {
            int c = path.charAt(i);
            if (this.safeCharacters.get(c)) {
                rewrittenPath.append((char) c);
            } else {
                try {
                    writer.write((char) c);
                    writer.flush();
                } catch (IOException var15) {
                    buf.reset();
                    continue;
                }

                byte[] ba = buf.toByteArray();

                for (int j = 0; j < ba.length; ++j) {
                    byte toEncode = ba[j];
                    rewrittenPath.append('%');
                    int low = toEncode & 15;
                    int high = (toEncode & 240) >> 4;
                    rewrittenPath.append(hexadecimal[high]);
                    rewrittenPath.append(hexadecimal[low]);
                }

                buf.reset();
            }
        }

        return rewrittenPath.toString();
    }
}
